package org.blog.helper;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;

public class GlobalHandlerExceptionResolver extends AbstractHandlerExceptionResolver {

	private static Logger logger = LoggerFactory.getLogger(GlobalHandlerExceptionResolver.class);

	@Override
	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		logger.warn("Resolving exception from handler [" + handler + "]: ", ex);
		// 判断是不是ajax请求
		if (HttpUtils.isAjax(request) || request.getHeader("Accept").contains("application/json")) {
			try {
				int code;
				if (ex instanceof IllegalArgumentException) {
					code = 400;

				} else if (ex instanceof BaseException) {
					code = ((BaseException) ex).getCode();
				} else {
					code = 500;
				}
				String result = (new Result<Object>(code)).toJSONString();
				response.getWriter().println(result);
				logger.info("response body: {}", result);

			} catch (IOException e) {
				e.printStackTrace();
			}

			return new ModelAndView();

		} else {
			if (ex instanceof IllegalArgumentException) {
				return new ModelAndView("400");
			}
			return new ModelAndView("500");
		}
	}

}
